package com.sky.service.UserService.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.AddressBookBusinessException;
import com.sky.mapper.user.*;
import com.sky.pojo.*;
import com.sky.result.Result;
import com.sky.service.UserService.OrderService;
import com.sky.utils.MapUtils;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class UserOrderServicelmpl implements OrderService {
    @Resource
    UserOrderMapper orderMapper;
    @Resource
    ShoppingCartMapper shoppingCartMapper;
    @Resource
    MerchantMapper merchantMapper;
    @Resource
    AddressBookMapper addressBookMapper;
    @Resource
    OrderDetailMapper orderDetailMapper;
    @Resource
    UserMapper userMapper;

    @Autowired
    private BeanValidatorPluginsConfiguration beanValidatorPluginsConfiguration;

    @Override
    public Result<String> getEstimatedDeliveryTime(String customerAddress, Integer shopId) {
        AtomicInteger i= new AtomicInteger();
         // 1.预计送达时间=当前时间+菜品制作时间+配送时间+预留时间（10分钟）
         // 从线程中获取 userId
        Long currentId = BaseContext.getCurrentId();
        List<Integer> byDishMakeTime = shoppingCartMapper.getByUserIdDishId(Math.toIntExact(currentId));
        List<Integer> bysetmealMakeTime = shoppingCartMapper.getByUserIdsetmeal(Math.toIntExact(currentId));
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算出来菜品时间
        int dishMakeTime = byDishMakeTime.stream().mapToInt(t->t).sum();
        //计算出来套餐时间
        int setmealMakeTime = bysetmealMakeTime.stream().mapToInt(t -> t).sum();
        //计算出来菜品制作总时间
        int sum = dishMakeTime+setmealMakeTime;

        Merchant merchant = merchantMapper.selectMerchant(Long.valueOf(shopId));
        String shopAddress = merchant.getShopAddress();
        //配送时间 用高德API
        Map<String, String> deliveryTime = MapUtils.gaodeTwoPointCostDistanceAndTime(shopAddress, customerAddress);
        Long l = Long.valueOf(deliveryTime.get("duration"));
        LocalDateTime localDateTime = now.plusSeconds(sum * 60).plusSeconds(l).plusSeconds(500);
        return Result.success(localDateTime.toString());
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public  Result<OrderSubmitVO> insertSubmint(OrdersSubmitDTO ordersSubmitDTO) {
        Long currentId = BaseContext.getCurrentId();
       // 查询 订单是否合法
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        AddressBook address =
                shoppingCartMapper.selectAddressAll(Math.toIntExact(ordersSubmitDTO.getAddressBookId()));
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        // 查询用户信息
        User byUserId = userMapper.getByUserId(currentId);
        // 获取地址
        orders.setAddress(address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getDetail());
        orders.setAddressBookId(ordersSubmitDTO.getAddressBookId());
        orders.setUserId(address.getUserId());
        orders.setUserName(byUserId.getName());
        orders.setConsignee(address.getConsignee());
        orders.setStatus(Orders.PENDING_PAYMENT); //1待付款
        orders.setNumber(UUID.randomUUID().toString().replaceAll("-", ""));
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID); // 0未支付
        orders.setPhone(address.getPhone());


        List<Integer> byDishMakeTime = shoppingCartMapper.getByUserIdDishId(Math.toIntExact(currentId));
        List<Integer> bysetmealMakeTime = shoppingCartMapper.getByUserIdsetmeal(Math.toIntExact(currentId));
       // bysetmealMakeTime.addAll(byDishMakeTime);
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算出来菜品时间
        int dishMakeTime = byDishMakeTime.stream().mapToInt(t->t).sum();
        //计算出来套餐时间
        int setmealMakeTime = bysetmealMakeTime.stream().mapToInt(t -> t).sum();
        //计算出来菜品制作总时间
        int sum = dishMakeTime+setmealMakeTime;
       orders.setMealTime(now.plusMinutes(sum));
       // 插入订单表的信息
        orderMapper.insertSubmint(orders);
      // 插入订单明细表信息
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(Math.toIntExact(currentId));
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);
        //当用户点击下单的时候 就删除购物车数据库中的信息
        shoppingCartMapper.deleteByUserId(currentId);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return Result.success(orderSubmitVO);
    }


}
